// © 2009 Microsoft Corporation.  All rights reserved.
# region Namespaces

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

using AjaxControlToolkit;
using UTL = Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Common;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.RiskService;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.UserControls;
using Microsoft.Security.Application;

# endregion

namespace Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Risks
{
    /// <summary>
    /// This page is the implementation for the Basic Search for Risk.
    /// </summary>
    public partial class BasicRiskSearch : System.Web.UI.Page
    {
        #region Handle Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            // Role CHECKING on every page load.
            if (!
                (
                // Not checking for Risk manager because Risk user is child of Risk manager.  
                // Parent inherits childs permissions.                
                     this.Context.User.IsInRole(ConfigurationManager.AppSettings["RiskEntryUser"].ToString())
                  || this.Context.User.IsInRole(ConfigurationManager.AppSettings["TrustedTaskUser"].ToString())
                )
               )
                Response.Redirect("../Errors/403.htm", true);
            else
            {
                if (
                (
                     !(
                     this.Context.User.IsInRole(ConfigurationManager.AppSettings["RiskEntryUser"].ToString())
                  || this.Context.User.IsInRole(ConfigurationManager.AppSettings["RiskManager"].ToString())
                  )
                  &&
                  (this.Context.User.IsInRole(ConfigurationManager.AppSettings["TrustedTaskUser"].ToString()))
                )
               )
                    ViewState["isFilter"] = 0; // YES TO FILTER
                else
                    ViewState["isFilter"] = 1; // NO TO FILTER
            }
            if (!IsPostBack)
            {
                LoadControlXML();
            }
            riskBasicSearchControl.FieldsXml = ViewState["XML"].ToString();
        }

        protected void riskBasicSearchControl_SearchFilterSelected(object sender, SearchFilterResultEventArgs e)
        {
            if (e.Result != null)
            {
                gridRiskList.PageIndex = 0;
                BindGrid();
            }
        }

        protected void obdsbasicRiskSearch_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            if (!e.ExecutingSelectCount && riskBasicSearchControl.SelectedFilterResult != null)
            {
                SearchFilterResult filterResult = riskBasicSearchControl.SelectedFilterResult;
                e.Arguments.MaximumRows = gridRiskList.PageSize;
                e.Arguments.StartRowIndex = (gridRiskList.PageIndex * gridRiskList.PageSize) + 1;
                e.InputParameters.Add("fieldName", filterResult.FieldName);
                e.InputParameters.Add("fieldoperator", filterResult.Operator);
                e.InputParameters.Add("value1", filterResult.Values[0]);

                if (filterResult.Values.Length > 1)
                    e.InputParameters.Add("value2", filterResult.Values[1]);
                else
                    e.InputParameters.Add("value2", null);

                if (ViewState["SortExpression"] == null)
                    e.InputParameters.Add("sortField", "RiskID");
                else
                    e.InputParameters.Add("sortField", ViewState["SortExpression"].ToString());

                e.InputParameters.Add("sortAscDesc", ViewState["SortAscDesc"]);

                e.InputParameters.Add("personID", ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId);
                e.InputParameters.Add("isRoleFilter", int.Parse(ViewState["isFilter"].ToString()));
            }
        }

        protected void obdsbasicRiskSearch_Selected(object sender, ObjectDataSourceStatusEventArgs e)
        {
            if (e.ReturnValue != null)
            {
                // To Display the record count found.
                if (e.ReturnValue.GetType().ToString() == "System.Int32")
                {
                    int rcount = (int)e.ReturnValue;
                    Page pge = (Page)this.Page;
                    gridRiskList.Caption = UTL.Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.RiskMessages", "RISKSEARCH_FILTERCAPTION1") + " "
                    + rcount.ToString() + " " +
                    UTL.Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.RiskMessages", "RISKSEARCH_FILTERCAPTION2");
                }
            }
        }

        protected void gridRiskList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridRiskList.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        protected void gridRiskList_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (ViewState["SortAscDesc"] != null)
                if ((int)ViewState["SortAscDesc"] == 0)
                    ViewState["SortAscDesc"] = 1;
                else
                    ViewState["SortAscDesc"] = 0;
            else
                ViewState["SortAscDesc"] = 0;

            ViewState["SortExpression"] = e.SortExpression;

            e.Cancel = true;
            BindGrid();
        }

        #endregion

        #region Search SOA Service layer

        /// <summary>
        /// Get the count for the search records found.
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="fieldoperator"></param>
        /// <param name="sortField"></param>
        /// <param name="sortAscDesc"></param>
        /// <param name="value1"></param>
        /// <param name="value2"></param>
        /// <returns></returns>
        public int GetSearchResultCount
            (
            string fieldName,
            string fieldoperator,
            string sortField,
            int sortAscDesc,
            string value1,
            string value2,
            int personID,
            int isRoleFilter
            )
        {
            RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
            // Declare local variables.
            int totalCount = riskServiceClient.BasicSearchRiskCount
                (
                fieldName,
                fieldoperator,
                value1,
                value2,
                personID,
                isRoleFilter
                );
            riskServiceClient.Close();

            return totalCount;
        }

        /// <summary>
        /// Gets the result for the search criteria.
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="fieldoperator"></param>
        /// <param name="sortField"></param>
        /// <param name="sortAscDesc"></param>
        /// <param name="value1"></param>
        /// <param name="value2"></param>
        /// <param name="maximumRows"></param>
        /// <param name="startRowIndex"></param>
        /// <returns></returns>
        public RiskInformation[] GetSearchResult(string fieldName, string fieldoperator, string sortField, int sortAscDesc, string value1, string value2, int maximumRows, int startRowIndex, int personID, int isRoleFilter)
        {
            RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
            // Declare local variables.
            RiskInformation[] riskCollection = riskServiceClient.BasicSearchRisk(fieldName, fieldoperator, sortField, sortAscDesc, maximumRows, startRowIndex, value1, value2, personID, isRoleFilter);
            riskServiceClient.Close();

            return riskCollection;
        }

        #endregion

        #region Helper Functions

        /// <summary>
        /// Load XML to bind controls.
        /// </summary>
        private void LoadControlXML()
        {
            //Better performance.
            StringBuilder concatenatedValue = new StringBuilder(500);
            XmlDocument xmlDoc = new XmlDocument();
            //Load the DeTrustedTaskUserfault xml.
            xmlDoc.Load(Server.MapPath(ConfigurationManager.AppSettings["PathforFilterXML"].ToString()));
            string completeXML = xmlDoc.OuterXml;

            RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
            ListItem[] riskClassificationOptions = riskServiceClient.GetRiskStatusOptions();

            //Replace Status Values
            foreach (ListItem temp in riskClassificationOptions)
                concatenatedValue.Append(@"<AllowedValue Key=""" + temp.Value + @""">" + AntiXss.XmlEncode(temp.Text.Trim()) + "</AllowedValue>" + Environment.NewLine);

            completeXML = completeXML.Replace("{#AllowedRiskStatusValues#}", concatenatedValue.ToString());

            // Replace Risk Group values.
            riskClassificationOptions = riskServiceClient.GetRiskGroups();
            concatenatedValue = null;
            concatenatedValue = new StringBuilder(500);

            //Replace Group Values
            foreach (ListItem temp in riskClassificationOptions)
                concatenatedValue.Append(@"<AllowedValue Key=""" + temp.Value + @""">" + AntiXss.XmlEncode(temp.Text.Trim()) + "</AllowedValue>" + Environment.NewLine);

            completeXML = completeXML.Replace("{#AllowedRiskGroupValues#}", concatenatedValue.ToString());

            ViewState["XML"] = completeXML;
        }

        /// <summary>
        ///  Handle CRV case scenerios to diplay Value or Unknown.
        /// </summary>
        /// <param name="crvValue"></param>
        /// <returns></returns>
        protected string ShowUnKnown(int crvValue)
        {
            string final = string.Empty;
            if (crvValue == -1)
                final = ConfigurationManager.AppSettings["DefaultTextRatings"].ToString();
            else
                final = crvValue.ToString();

            return final;
        }
        /// <summary>
        ///  Handle PCRV case scenerios to diplay Value or Unknown.
        /// </summary>
        /// <param name="crvValue"></param>
        /// <returns></returns>
        protected string ShowUnKnown(Decimal crvValue)
        {
            string final = string.Empty;
            if (crvValue == -1)
                final = ConfigurationManager.AppSettings["DefaultTextRatings"].ToString();
            else
                final = crvValue.ToString();

            return final;
        }

        /// <summary>
        /// Bind the grid to data source.
        /// </summary>
        private void BindGrid()
        {
            gridRiskList.DataSource = obdsbasicRiskSearch;
            gridRiskList.DataBind();
        }

        #endregion

        #region Error handler
        /// <summary>
        /// Error Handler for the page.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Page_Error(object sender, EventArgs e)
        {
            System.Exception error = Server.GetLastError();
            throw new HttpException(500, "Unhandled Exception.", error);
        }
        #endregion
    }
}
